package com.dg11185.nearshop.baidumap;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Dialog;
import android.content.Context;
import android.view.View.MeasureSpec;
import android.widget.TextView;

import com.android.nearshop.R;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.dg11185.libs.ormlite.android.apptools.OpenHelperManager;
import com.dg11185.libs.ormlite.dao.Dao;
import com.dg11185.libs.utils.string.StringUtils;
import com.dg11185.nearshop.app.ViewUtils;
import com.dg11185.nearshop.dbHelper.OrmLiteHelper;
import com.dg11185.nearshop.net.NetCacheClient;
import com.dg11185.nearshop.net.entity.Area;
import com.dg11185.nearshop.net.request.CountByAreaRequest;
import com.dg11185.nearshop.net.response.CountByAreaResponse;
import com.dg11185.nearshop.net.response.NetStatus;

public class NearshopHelper {

    /** 数据库 */
    private OrmLiteHelper databaseHelper = null;// 底包数据库helper

    private List<Area> areas = null;

    private Map<String, String> areaCountMap = null; // key-areaNum，
                                                     // value-countNum

    private Map<String, BitmapDescriptor> descriptorMap = null; // key-areaNum,
                                                                // value-bitmap

    private Context mActivity = null;

    private BaiduMap mBaiduMap = null;

    private String industryId = "";

    private Dialog loadingDialog = null;
    
    public NearshopHelper(Context activity, BaiduMap mBaiduMap) {
        this.mActivity = activity;
        this.mBaiduMap = mBaiduMap;
        areaCountMap = new HashMap<String, String>();
        descriptorMap = new HashMap<String, BitmapDescriptor>();
        loadingDialog = ViewUtils.createLoadingDialog(mActivity);
        initAreaData();
    }

    public void initAreaData(){
        // 获取地区数据
        if (areas == null) {
            Dao<Area, Integer> areaDao = getHelper().getAreaDao();
            try {
                areas = areaDao.queryForAll();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    /**
     * 调用该方法的三个时间点： 1、刚进入地图摇摇界面 2、地图缩小 3、点击商家分类
     */
    public void initShopNumOverlay(String areaNum, String industryId) {

        // 获取每个地区改分类的商家

        if(industryId == null){
            industryId = "";
        }
        if (!this.industryId.equals(industryId) || areaCountMap.size() < 1) {
            CountByAreaRequest request = new CountByAreaRequest(areaNum);
            if (!StringUtils.isBlank(industryId)) {
                request.add(request.INDUSTRY_ID, industryId);
            }
            request.encryption();
            loadingDialog.show();
            request.setActionListener(new CountByAreaRequest.ActionListener<CountByAreaResponse>() {

                @Override
                public void onSuccess(CountByAreaResponse result) {
                    loadingDialog.dismiss();
                    if (result.status == NetStatus.SUCCESS) {
                        
                        for (int a = 0; a < result.areaCounts.size(); a++) {
                            areaCountMap.put(result.areaCounts.get(a).areaNum, result.areaCounts.get(a).countNum);
                        }
                        createDescriptor();
                        displayOverlay();
                    }
                }

                @Override
                public void onFailure(int resultCode) {
                    loadingDialog.dismiss();
                }
            });
            NetCacheClient.httpCacheGet(request);
        } else {
            displayOverlay();
        }
        this.industryId = industryId;
    }

    /**
     * 先销毁上一次地图图层的icon，在新建当前需要的icon
     */
    private void createDescriptor() {
        if (descriptorMap.size() > 0) {
            Set<Entry<String, BitmapDescriptor>> set = descriptorMap.entrySet();
            Iterator<Entry<String, BitmapDescriptor>> it = set.iterator();
            while (it.hasNext()) {
                Entry<String, BitmapDescriptor> entry = it.next();
                entry.getValue().recycle();
            }
        }
        for (int index = 0; index < areas.size(); index++) {
            TextView view = new TextView(mActivity);
            view.setPadding(10, 10, 10, 10);
            view.setText(areaCountMap.get(areas.get(index).areaNum) + " 家");
            view.setTextColor(mActivity.getResources().getColor(R.color.white));
            view.setBackgroundColor(mActivity.getResources().getColor(R.color.main_red));
            view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
            view.buildDrawingCache();
            BitmapDescriptor descriptor = BitmapDescriptorFactory.fromView(view);
            descriptorMap.put(areas.get(index).areaNum, descriptor);
        }
    }

    /**
     * 在地图上显示商家图层,
     */
    public void displayOverlay() {
        mBaiduMap.clear();
        for (int index = 0; index < areas.size(); index++) {
            if(Integer.parseInt(areaCountMap.get(areas.get(index).areaNum)) > 0){
                LatLng poi = new LatLng(areas.get(index).latitude + 0.005, areas.get(index).longitude + 0.005);
                OverlayOptions options = new MarkerOptions().zIndex(index).position(poi)
                        .icon(descriptorMap.get(areas.get(index).areaNum));
                mBaiduMap.addOverlay(options);
            }
        }
    }

    public List<Area> getAreas(){
        return areas;
    }
    
    /**
     * 返回areaNum地区的商家数量，根据商家数量决定地图的缩放等级
     */
    public int getMerchantCount(String areaNum){
        String count = areaCountMap.get(areaNum);
        if(!StringUtils.isBlank(count)){
            return Integer.parseInt(count);
        }
        return 0;
    }
    /**
     * You'll need this in your class to get the helper from the manager once
     * per class.
     */
    private OrmLiteHelper getHelper() {

        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(mActivity, OrmLiteHelper.class);
        }
        return databaseHelper;
    }

    /**
     * 回收地图图层的descriptor,释放数据库资源
     */
    public void releseDbHelper() {

        Set<Entry<String, BitmapDescriptor>> set = descriptorMap.entrySet();
        Iterator<Entry<String, BitmapDescriptor>> it = set.iterator();
        while (it.hasNext()) {
            Entry<String, BitmapDescriptor> entry = it.next();
            entry.getValue().recycle();
        }
        /*
         * You'll need this in your class to release the helper when done.
         */
        if (databaseHelper != null && mActivity != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }
    }

    public void onZoomClicked(int zoomLevel) {
        
    }
}
